// pages/goodsList/goodsList.js
//点击首页的场馆跳转的页面
let url_js = require("../../utils/url.js");
var common_js = require("../../utils/common.js");
var const_js = require("../../utils/const.js");
var user_js = require("../../utils/user.js");
var sys_js = require("../../utils/system.js");
var cart_js = require("../../utils/cart.js");
var ubt_js = require("../../utils/ubt.js");
var name_js = require("../../utils/ubtButtonName.js");
var api = require("../../utils/apiRequest.js");

Page({

  /**
   * 页面的初始数据
   */
  data: {
    sysInfo: null,
    userInfo: null,
    pageScrollTop: 0,
    containerTouchmove: '',
    goodsPropertyInfo: {
      pageShow: false, //页面展示
      dismiss: false, //手动设置隐藏，当属性页面隐藏完成后，pageShow设置false
    },
    addCartSelctedGoodsInfo: null, //当前添加购物车的商品，只有当有多种规格时有数据
    item: null,
    contentStatus: -1,
    pageInfo: {
      curPage: 1,
      pageSize: 10,
      noMore: false
    },
    goodsList: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    //业务埋点
    ubt_js.myPageView(common_js.currentPageName(), options);
    //1.禁止转发
    wx.hideShareMenu();
    //2.初始化数据
    this.initData(options);
    //3.根据item的linkType类型去请求数据
    this.requestToGetProductList(this.data.item.frontCategoryId, this.data.item.tagId, this.data.pageInfo.curPage, this.data.pageInfo.pageSize);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    // 业务埋点
    ubt_js.myPageViewOut(common_js.currentPageName());
  },

  //初始化数据
  initData: function(options) {
    //1.解析数据
    let tmpItem = common_js.jsonParse(options.item);
    let tempUserInfo = user_js.userInfo();
    if (tmpItem) {
      //2.设置数据
      this.setData({
        item: tmpItem,
        sysInfo: sys_js.systemInfo(),
        userInfo: tempUserInfo
      });
      //3.设置title
      wx.setNavigationBarTitle({
        title: tmpItem.name
      });
    }
  },

  //展现tag或者category对应的商品
  requestToGetProductList: function(categoryId, tagId, curPage, pageSize, pullDownRefresh) {
    let data = {
      categoryId: categoryId ? categoryId : '',
      cityId: this.data.userInfo.ztd.cityId,
      code: this.data.userInfo.code,
      curPage: curPage,
      pageSize: pageSize,
      shopId: this.data.userInfo.ztd.id,
      tagId: tagId ? tagId : ''
    };
    api.wxRequest(url_js.productListUrl, data).then(res => {
      this.handleProductListData(res, curPage, pullDownRefresh);
      common_js.hidePageLoading(pullDownRefresh);
    }).catch(err => {
      common_js.hidePageLoading(pullDownRefresh);
      common_js.log(err);
    });
  },

  //处理tag对应的商品数据
  handleProductListData: function(res, curPage, pullDownRefresh) {
    //设置数据
    var tmpList = this.data.goodsList;
    if (pullDownRefresh) {
      tmpList = [];
    }
    //pageInfo
    var tmpPageInfo = this.data.pageInfo;
    if (res.page.pages <= curPage) {
      tmpPageInfo.noMore = true;
    } else {
      tmpPageInfo.curPage++;
    }
    //list
    if (res.result.length > 0) {
      tmpList = tmpList.concat(res.result);
      this.setData({
        contentStatus: 1,
        pageInfo: tmpPageInfo,
        goodsList: tmpList
      });
    } else {
      this.setData({
        contentStatus: 1,
        pageInfo: tmpPageInfo
      });
    }
  },


  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    if (this.data.contentStatus == -1) return;
    //2.reset data
    var tmpPageInfo = this.data.pageInfo;
    tmpPageInfo.curPage = 1;
    tmpPageInfo.noMore = false;
    this.setData({
      pageInfo: tmpPageInfo
    });
    //refresh
    this.requestToGetProductList(this.data.item.frontCategoryId, this.data.item.tagId, this.data.pageInfo.curPage, this.data.pageInfo.pageSize, true);
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    if (this.data.pageInfo.noMore) return;
    //1. request
    this.requestToGetProductList(this.data.item.frontCategoryId, this.data.item.tagId, this.data.pageInfo.curPage, this.data.pageInfo.pageSize);
  },

  // 监听用户滑动页面事件
  onPageScroll: function(e) {
    var topY = e.scrollTop + "px";
    this.setData({
      pageScrollTop: topY
    });
  },

  //按钮点击事件
  //禁止滚动
  preventTouchMove: function() {},

  //商品属性选择确定
  onGoodsPropertyEnsure: function(e) {
    //消失
    this.onGoodsPropertyHidden();
    //添加购物车
    if (e) {
      var item = e.detail;
      //限时抢购单独判断
      if (this.data.addCartSelctedGoodsInfo.type == 2) {
        var skuItem = item.sku;
        var cartLimitCount = cart_js.limitSkuCountWithSkuId(skuItem.id);
        var isAlert = (cartLimitCount == 0) ? (item.count > skuItem.userBuyLimit) : (cartLimitCount >= skuItem.userBuyLimit);
        if (isAlert) {
          common_js.showModal("每人限购" + skuItem.userBuyLimit + "件，超过的件数将以原价支付！", null, true, null, "我知道了", () => {
            this.requestToAddCart(item.sku, this.data.addCartSelctedGoodsInfo.id, item.sku.id, item.count);
          })
          return;
        }
      }
      this.requestToAddCart(item.sku, this.data.addCartSelctedGoodsInfo.id, item.sku.id, item.count);
    }
  },

  //商品属性选择
  onGoodsPropertyHidden: function(e) {
    var tmpGoodsPropertyInfo = this.data.goodsPropertyInfo;
    tmpGoodsPropertyInfo.pageShow = false;
    tmpGoodsPropertyInfo.dismiss = false,
      this.setData({
        containerTouchmove: '',
        goodsPropertyInfo: tmpGoodsPropertyInfo
      });
  },

  //隐藏商品属性页面
  onHidePropertyPageView: function(e) {
    var tmpGoodsPropertyInfo = this.data.goodsPropertyInfo;
    tmpGoodsPropertyInfo.dismiss = true;
    this.setData({
      goodsPropertyInfo: tmpGoodsPropertyInfo
    });
  },

  //添加商品
  onAddGoods: function(e) {
    if (!user_js.isLogin()) {
      wx.navigateTo({
        url: '../loginIndex/loginIndex'
      });
      return
    }

    var index = e.currentTarget.dataset.index;
    var item = this.data.goodsList[index];
    if (item.skuList && item.skuList.length > 1) {
      if (item.dimensions.length == 0) {
        common_js.showToast("商品多规格属性不存在！");
        return;
      }
      //多规格,选择规格加入购物车
      //展示多规格商品
      var tmpGoodsPropertyInfo = this.data.goodsPropertyInfo;
      tmpGoodsPropertyInfo.pageShow = true;
      this.setData({
        addCartSelctedGoodsInfo: item,
        goodsPropertyInfo: tmpGoodsPropertyInfo,
        containerTouchmove: 'preventTouchMove'
      });
    } else {
      //单一规格,直接添加购物车
      if (item.skuList == 0) {
        common_js.showToast("商品sku不存在");
        return;
      }
      //限时抢购单独判断
      if (item.type == 2) {
        var skuItem = item.skuList[0];
        var cartLimitCount = cart_js.limitSkuCountWithSkuId(skuItem.id);
        var isAlert = (cartLimitCount == 0) ? (item.count > skuItem.userBuyLimit) : (cartLimitCount >= skuItem.userBuyLimit);
        if (isAlert) {
          common_js.showModal("每人限购" + skuItem.userBuyLimit + "件，超过的件数将以原价支付！", null, true, null, "我知道了", () => {
            this.requestToAddCart(item.skuList[0], item.id, item.skuList[0].id, 1);
          })
          return;
        }
      }
      this.requestToAddCart(item.skuList[0], item.id, item.skuList[0].id, 1);
    }
  },

  //增加购物车
  requestToAddCart: function(skuItem, productId, skuId, num) {
    let data = {
      cityId: this.data.userInfo.ztd.cityId,
      code: user_js.getCode(),
      num: num,
      productId: productId,
      shopId: this.data.userInfo.ztd.id,
      skuId: skuId
    };
    api.wxRequest(url_js.cartAddUrl, data).then(res => {
      this.handleAddCartData(res, skuItem, skuId, num);
    }).catch(err => {
      common_js.log(err);
    });
  },

  //处理添加购物车
  handleAddCartData: function(res, skuItem, skuId, num) {
    cart_js.addCart(skuItem, skuId, num);
    common_js.showToast("添加购物车成功");
  },

  //商品详情
  onGoodsDetail: function(e) {
    var index = e.currentTarget.dataset.index;
    var item = this.data.goodsList[index];
    wx.navigateTo({
      url: '../goodsDetails/goodsDetails?productId=' + item.id
    });
  }
})